package com.bicon.botu.account.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bicon.botu.account.dto.ResourcesDto;
import com.bicon.botu.account.entity.Resources;
import com.bicon.botu.account.entity.RoleResources;
import com.bicon.botu.account.mapper.ResourcesMapper;
import com.bicon.botu.account.service.IResourcesService;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.core.base.common.utils.BeanMapper;
import com.bicon.botu.core.base.common.utils.NodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @auther 裴志鹏
 * @date 2017/11/30 11:35
 */
@Slf4j
@Service
public class ResourcesServiceImpl extends ServiceImpl<ResourcesMapper, Resources> implements IResourcesService {

    /**
     * 新增资源
     *
     * @param name     资源名
     * @param parentId 资源父ID
     * @param sort     排序
     * @param path     资源路径
     * @param type     账户类型：0：前台账户，1：后台账户
     * @return
     */
    @Override
    public BaseResult add(String name, String parentId, String sort, String path, String type) {
        Resources resources = new Resources();
        resources.setName(name);
        resources.setParentId(parentId);
        resources.setSort(Integer.parseInt(sort));
        resources.setPath(path);
        resources.setType(type);
        resources.preInsert();
        boolean result = resources.insert();
        if (result) {
            log.info("add resources success");
            return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
        }
        log.info("add resources fail");
        return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
    }

    /**
     * 删除资源
     *
     * @param idJson 资源id集合
     * @param type   账户类型：0：前台账户，1：后台账户
     * @return
     */
    @Override
    public BaseResult delete(String idJson, String type) {
        String[] idList = idJson.split(",");
        for (int i = 0; i < idList.length; i++) {
//          校验资源是否与角色关联
            Integer roleResources = new RoleResources().selectCount(new EntityWrapper<RoleResources>().eq("resources_id", idList[i]).eq("type", type).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
            if (roleResources != 0 && roleResources > 0) {
                return new BaseResult(Constants.RESPONSE_CODE_601, "角色已与该资源关联，请先删除角色资源关系");
            }
//          删除资源
            Resources resources = new Resources();
            resources.setId(idList[i]);
            resources.setType(type);
            resources.setLogicDelete(Constants.DEL_LOGIC_DELETE);
            resources.preUpdate();
            boolean result = resources.updateById();
            if (!result) {
                log.info("delete resource fail");
                return new BaseResult(Constants.RESPONSE_CODE_602, Constants.RESPONSE_MESSAGE_602);
            }
//          逻辑删除资源下的子资源
            List<Resources> resourcesList = new Resources().selectList(new EntityWrapper<Resources>().eq("parent_id", idList[i]).eq("type", type).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
            if (!resourcesList.isEmpty() && resourcesList.size() > 0) {
                for (Resources r : resourcesList) {
                    Resources resources1 = new Resources();
                    resources1.preUpdate();
                    resources1.setLogicDelete(Constants.DEL_LOGIC_DELETE);
                    resources1.update(new EntityWrapper<Resources>().eq("parent_id", r.getId()).eq("type", type));
                    r.preUpdate();
                    r.setLogicDelete(Constants.DEL_LOGIC_DELETE);
                    r.updateById();
                }
            }
        }
        log.info("delete resource success");
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }

    /**
     * 修改资源
     *
     * @param id   资源id
     * @param path 资源路径
     * @param name 资源名
     * @param type 账户类型：0：前台账户，1：后台账户
     * @return
     */
    @Override
    public BaseResult update(String id, String path, String name, String type) {
        Resources resources = new Resources();
        resources.preUpdate();
        resources.setId(id);
        resources.setPath(path);
        resources.setName(name);
        resources.setType(type);
        boolean result = resources.updateById();
        if (result) {
            return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
        } else {
            return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
        }
    }

    /**
     * 查询树形资源
     *
     * @return
     */
    @Override
    public BaseResult selectResourcesAll(String type) {
        try {
            List<Resources> list = new Resources().selectList(new EntityWrapper<Resources>().eq("type", type).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
            List<ResourcesDto> resourcesDtos = BeanMapper.mapList(list, ResourcesDto.class);
            List<ResourcesDto> resultList = new NodeUtil<ResourcesDto>().getChildNodes(resourcesDtos);
            if (resultList != null && resultList.size() > 0) {
                return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, resultList);
            } else {
                return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, list);
            }
        } catch (Exception e) {
            return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
        }
    }

    /**
     * 分页获取资源列表
     *
     * @param type    账户类型：0：前台账户，1：后台账户
     * @param current 当前页
     * @param size    每页记录数
     * @return
     */
    @Override
    public Page<Resources> getPagingResources(String type, int current, int size) {
        return new Resources().selectPage(new Page<>(current, size), new EntityWrapper<Resources>().eq("type", type).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
    }
}
